/**
 * @author: yyq
 * @date: 2025年3月14日 18:53:15
 * @description: 
 */
package com.sheepone.monitor.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.sheepone.monitor.anno.ChannelHandlerOrder;

import io.netty.channel.ChannelHandler;

/**
 * @author: yyq
 * @date: 2025年3月14日 18:53:15
 * @description:
 */
public class ChannelHandlerSorter {
    private static final Comparator<ChannelHandler> comparator = new Comparator<>() {
        @Override
        public int compare(ChannelHandler h1, ChannelHandler h2) {
            return Integer.compare(getOrder(h1), getOrder(h2));
        }

        private int getOrder(ChannelHandler handler) {
            ChannelHandlerOrder orderAnnotation = handler.getClass().getAnnotation(ChannelHandlerOrder.class);
            if (orderAnnotation != null) {
                return orderAnnotation.value();
            }
            return Integer.MAX_VALUE;
        }

    };

    private ChannelHandlerSorter() {

    }

    public static void sort(Collection<ChannelHandler> handlers) {
        if (handlers == null || handlers.isEmpty()) {
            return;
        }
        List<ChannelHandler> list = null;
        if (handlers instanceof List) {
            list = (List<ChannelHandler>) handlers;
        } else {
            list = new ArrayList<>(handlers);
        }
        Collections.sort(list, comparator);

    }
}
